package com.study.ibatis.io.proxy;

import com.study.ibatis.io.cfg.Configuration;
import com.study.ibatis.io.cfg.Mapper;
import com.study.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;

public class MapperProxy implements InvocationHandler {
    //mapper的Key是全限定类名加方法名
    private Map<String,Mapper> mappers;
    private Connection conn;
    public MapperProxy(Map<String,Mapper> mappers,Connection conn){
        this.mappers=mappers;
        this.conn=conn;
    }
    /**
     * 用于方法增强(直接调用)
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName=method.getName();
        String clazzName=method.getDeclaringClass().getName();
        String key=clazzName+"."+methodName;
        Mapper mapper=mappers.get(key);
        if(mapper==null)
        {
            throw new IllegalArgumentException("传入的参数有误!");
        }

        return new Executor().selectList(mapper,conn);
    }
}
